import axios from 'axios'
import router from '@/router'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import store from '@/store'

const instance = axios.create({
    // baseURL: 'http://toutiao.itheima.net/',
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 3000
})

// 添加请求拦截器
instance.interceptors.request.use(config => {
    config.headers.Authorization = 'Bearer ' + getToken()
    return config
}, error => {
    return Promise.reject(error)
})

// 添加响应拦截器
instance.interceptors.response.use(response => {
    if (response.data instanceof Blob) return response.data
    if (response.data.success) {
        if (!(response.data.message === '获取资料成功')) Message.success(response.data.message)
    } else {
        Message.error(response.data.message)
    }

    return response
}, async error => {
    if (error.response.status === 401) {
        await store.commit('user/logout')
        this.$router.push(`/login`)
    }
    return Promise.reject(error)
})

export default instance
